package com.yunji.app.order;

import com.yunji.common.base.BaseController;
import com.yunji.common.base.response.Response;
import com.yunji.common.base.response.ResponseHelper;
import com.yunji.common.event.EventConstant;
import com.yunji.common.event.RedissonEventBus;
import com.yunji.common.event.entity.RedissonEvent;
import com.yunji.common.utils.TimeUtils;
import com.yunji.coupon.bo.OrderAmtBO;
import com.yunji.coupon.dto.OrderAndCouponDTO;
import com.yunji.coupon.vo.CouponVO;
import com.yunji.order.bo.ListOrderMemberBO;
import com.yunji.order.business.OrderBusiness;
import com.yunji.order.command.order.OrderStateMachine;
import com.yunji.order.context.convert.OrderConvert;
import com.yunji.order.domain.OrderDO;
import com.yunji.order.domain.OrderDetailDO;
import com.yunji.order.dto.OrderCreateDTO;
import com.yunji.order.dto.OrderPageDTO;
import com.yunji.order.dto.cmd.OrderPaidCommandDTO;
import com.yunji.order.emuns.OrderCancelTypeEnum;
import com.yunji.order.emuns.OrderStatusEnum;
import com.yunji.order.service.OrderService;
import com.yunji.order.vo.OrderVO;
import com.yunji.order.wechat.WechatCallbackDTO;
import com.yunji.order.wechat.WechatTrade;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * @author : peter-zhu
 * @date : 2025/3/29 14:18
 * @description : 订单
 */
@RestController
@Api(tags = "移动端-订单模块")
@RequestMapping("/gateway/order")
public class AppOrderController extends BaseController {
    @Resource
    private OrderBusiness orderBusiness;

    @Resource
    private OrderService orderService;

    @ApiOperation("同步历史订单")
    @GetMapping("/syncHistoryOrder")
    public Response<?> syncHistoryOrder() throws Exception {
        OrderPageDTO orderPageDTO = new OrderPageDTO();
        orderPageDTO.setExport(true);
        List<OrderDO> orderDOS = orderService.orderScopeList(orderPageDTO);
        for (OrderDO orderDO : orderDOS) {
            List<OrderDetailDO> details = orderService.getOrderDetailsByOid(orderDO.getOrderId());
            RedissonEventBus.getInstance().publishAsync(new RedissonEvent<>(EventConstant.ORDER_VISUAL_QUEUE_KEY,
                    OrderConvert.convertQueueDTO(orderDO, details)));
        }
        return ResponseHelper.success();
    }

    @ApiOperation("模拟支付成功后的微信回调(前端不用关注)")
    @GetMapping("/testPayCallBack/{orderCode}")
    public Response<?> testPayCallBack(@PathVariable("orderCode") String orderCode) {
        WechatCallbackDTO peterTest = new WechatCallbackDTO(true, orderCode, "peter_test", TimeUtils.zoneDate());
        OrderDO orderByCode = orderBusiness.getOrderByCode(orderCode);
        return ResponseHelper.success(OrderStateMachine.statusChange(new OrderPaidCommandDTO(orderByCode, OrderStatusEnum.PAY_SUCCESS, peterTest)));
    }

    @ApiOperation("下单时计算订单相关金额(如果传优惠券计算优惠券金额)/缓存数据算金额性能高")
    @PostMapping("/getOrderAmt")
    public Response<OrderAmtBO> getOrderAmt(@Valid @RequestBody OrderAndCouponDTO dto) {
        return ResponseHelper.success(orderBusiness.getOrderAmt(dto.getCabinetId(), dto.getOrderDetails(), dto.getCouponId()));
    }

    @ApiOperation("下单时最优惠的优惠券或选择优惠券/优惠券发布信息不是基础数据,无法缓存性能差")
    @PostMapping("/getOptimalCoupon")
    public Response<CouponVO> getOptimalCoupon(@Valid @RequestBody OrderAndCouponDTO dto) {
        return ResponseHelper.success(orderBusiness.getOptimalCoupon(dto));
    }

    @ApiOperation("下单时选择优惠券")
    @GetMapping("/getSelectCoupon/{couponId}")
    public Response<CouponVO> getSelectCoupon(@PathVariable Long couponId) {
        return ResponseHelper.success(orderBusiness.getSelectCoupon(couponId));
    }

    @ApiOperation("订单下单")
    @PostMapping(value = "/createOrder")
    public Response<Long> createOrder(@Valid @RequestBody OrderCreateDTO dto) {
        return ResponseHelper.success(orderBusiness.createOrder(dto));
    }

    @ApiOperation("订单支付")
    @PostMapping("/pay/{orderId}")
    // @ApiImplicitParam(name = "tradeCode", value = "订单ID", dataType = "Integer", dataTypeClass = Integer.class)
    public Response<WechatTrade> pay(@PathVariable @NotNull Long orderId) {
        return ResponseHelper.success(orderBusiness.pay(orderId));
    }

    @ApiOperation("小程序APP获取订单列表")
    @PostMapping("/listByPage")
    public Response<List<OrderVO>> listByPage(@RequestBody ListOrderMemberBO order) {
        List<OrderVO> list = orderBusiness.appGetOrderList(order);
        return ResponseHelper.successWithPage(list);
    }

    @ApiOperation("获取订单详细信息")
    @GetMapping(value = "/queryById")
    public Response<OrderVO> getInfo(@RequestParam("id") Long id) {
        OrderVO order = orderBusiness.appGetOrder(id);
        return ResponseHelper.success(order);
    }

    @ApiOperation("删除订单")
    @PostMapping(value = "/deleteOrder")
    public Response<String> deleteOrder(@RequestParam(name = "orderId") Long orderId) {
        orderBusiness.deleteMemberOrder(orderId);
        return ResponseHelper.success();
    }

    @ApiOperation("关闭订单")
    @PostMapping(value = "/closedOrder")
    public Response<String> cancelOrder(@RequestParam(name = "orderId") Long orderId) {
        orderBusiness.cancelOrder(orderId, OrderCancelTypeEnum.MANUAL);
        return ResponseHelper.success();
    }
}
